/*
* 设备管理模块
*/
const express = require('express');
const router = express.Router();
// 引入数据库
const db = require("../../../config/db");
// 引入时间包
const moment = require("moment");
// 引入方法库
const { toCamelCase, toUnderlineCase, verifyToken} = require("../../../config/utils");
// 引入日志
const log = require("../../log");

// 查询设备列表
router.get('/list', async (req, res) => {
    console.log("===========查询设备列表接口============");
    // 获取参数
    let { pageNum, pageSize, machineryCode, machineryName } = req.query;
    // 拼接sql语句
    let sql = "select * from dv_machinery";
    let sql_where = ` where 1=1`;
    if(machineryCode){
        sql_where += ` and machinery_code like '%${machineryCode}%'`;
    }
    if(machineryName){
        sql_where += ` and machinery_name like '%${machineryName}%'`;
    }
    if(machineryCode || machineryName ){
        sql += sql_where;
    }
    
    // 分页
    sql += ` limit ${(pageNum-1)*pageSize}, ${pageSize}`;
    // 查询数据库
    db.query("查询设备列表", sql, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询设备列表失败", data: err});
            return;
        }
        // 查询总数
        db.query("查询设备总数", `select count(*) as count from dv_machinery ${sql_where}`, (err, count)=>{
            if(err){
                res.send({code: 500, msg: "查询设备总数失败", data: err});
                return;
            }
            if(result.length > 0){
                 // 变量Json数组key转成下划线第一个大写
                 result = result.map(item => {
                    return toCamelCase(item)
                })
                res.send({code: 200, msg: "查询设备列表成功", rows: result, total: count[0].count});
            }else{
                res.send({code: 200, msg: "查询设备列表成功", data: [], total: 0});
            }
        })
    })
})

// 添加设备
router.post("/", async (req, res) => {
    console.log("===========添加设备接口============");
    // 获取参数
    let { machineryCode, machineryName, machinerySpec, machineryBrand, remark, status, machineryTypeId, workshopId } = req.body;
     // 获取创建人
     let {username} = verifyToken(req.headers.authorization);
     // 获取创建时间
     let createTime = moment().format("YYYY-MM-DD HH:mm:ss");
     // 判断设备编码
     db.query("查询设备编码是否重复", `select * from dv_machinery where machinery_code='${machineryCode}'`, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询设备编码是否重复失败", data: err});
            return;
        }
        if(result.length > 0){
            res.send({code: 500, msg: "生产工序编码已存在", data: []});
            return;
        }

        // 根据车间id，设备类型id  查询车间名称,设备类型名称
        let sql_select = `select workshop_name from md_workshop where workshop_id='${workshopId}' union all select machinery_type_name from dv_machinery_type where machinery_type_id='${machineryTypeId}'`;
        db.query("查询车间名称 联合查询 设备类型", sql_select, (err, workshop_result)=>{
            if(err){
                res.send({code: 500, msg: "车间名称,设备类型名称,失败", data: err});
                return;
            }
            if(workshop_result.length > 0){
                // 车间名称
                let workshop_name = workshop_result[0].workshop_name;
                // 设备类型名称
                let machinery_type_name = workshop_result[1].workshop_name;
                // 插入数据库
                let sql = `insert into dv_machinery (machinery_code, machinery_name, status, machinery_type_id, workshop_id, workshop_name, machinery_type_name, machinery_spec, machinery_brand, remark, create_by, create_time) 
                values('${machineryCode}', '${machineryName}', '${status}', '${machineryTypeId}', '${workshopId}', '${workshop_name}', '${machinery_type_name}',
                ${machinerySpec ? "'"+machinerySpec+"'" : null}, ${machineryBrand ? "'"+machineryBrand+"'" : null}, ${remark ? "'"+remark+"'" : null}, 
                '${username}', '${createTime}')`;
                db.query("添加设备", sql, (err, result)=>{
                    if(err){
                        res.send({code: 500, msg: "添加设备失败", data: err});
                        return;
                    }
                    if(result.affectedRows > 0){
                        res.send({code: 200, msg: "添加设备成功", data: []});
                    }else{
                        res.send({code: 500, msg: "添加设备失败", data: []});
                    }
                })
            }
        })
     })
})

// 查询单个设备表
router.get(/^\/(\d+)$/, (req, res) => {
    console.log("===========查询单个设备表接口，正则匹配============");
    let url_arr = req.url.split("/");
    const machinery_id = url_arr[url_arr.length - 1];
    // 查询数据库
    db.query("查询单个设备表", `select * from dv_machinery where machinery_id = '${machinery_id}'`, (err, result) => {
        if (err) {
            res.send({code: 500, msg: '查询单个设备表失败', data: err})
            return
        }
        if(result.length > 0) {
           // 变量Json数组key转成下划线第一个大写
            result = result.map(item => {
                item.params = {};
                item.children = [];
                return toCamelCase(item)
            })
            result = result[0]
        }
        res.send({
            code: 200,
            msg: '查询成功',
            data: result
        })
    })
    
})

// 修改设备
router.put("/", async (req, res) => {
    console.log("===========修改设备接口============");
    // 获取参数
    let { machineryCode, machineryName, machinerySpec, machineryBrand, remark, status, machineryTypeId, workshopId, machineryId } = req.body;
     // 获取创建人
     let {username} = verifyToken(req.headers.authorization);
     // 获取更新时间
     let updateTime = moment().format("YYYY-MM-DD HH:mm:ss");
     // 判断设备编码
     db.query("查询设备编码是否重复", `select * from dv_machinery where machinery_code='${machineryCode}' and machinery_id != '${machineryId}'`, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询设备编码是否重复失败", data: err});
            return;
        }
        if(result.length > 0){
            res.send({code: 500, msg: "生产工序编码已存在", data: []});
            return;
        }

        // 根据车间id，设备类型id  查询车间名称,设备类型名称
        let sql_select = `select workshop_name from md_workshop where workshop_id='${workshopId}' union all select machinery_type_name from dv_machinery_type where machinery_type_id='${machineryTypeId}'`;
        db.query("查询车间名称 联合查询 设备类型", sql_select, (err, workshop_result)=>{
            if(err){
                res.send({code: 500, msg: "车间名称,设备类型名称,失败", data: err});
                return;
            }
            if(workshop_result.length > 0){
                // 车间名称
                let workshop_name = workshop_result[0].workshop_name;
                // 设备类型名称
                let machinery_type_name = workshop_result[1].workshop_name;
                // 更新sql数据库
                let sql_update = `update dv_machinery set machinery_code = '${machineryCode}', machinery_name = '${machineryName}', status = '${status}',
                machinery_type_id = '${machineryTypeId}', workshop_id = '${workshopId}', workshop_name= '${workshop_name}', machinery_type_name = '${machinery_type_name}',
                machinery_spec = ${machinerySpec ? "'"+machinerySpec+"'" : null}, machinery_brand = ${machineryBrand ? "'"+machineryBrand+"'" : null}, 
                remark =  ${remark ? "'"+remark+"'" : null}, update_by = '${username}', update_time = '${updateTime}'
                where machinery_id = '${machineryId}'`
                // 执行sql
                db.query("修改设备表", sql_update, (err, result)=>{
                    if(err){
                        res.send({code: 500, msg: "修改设备表失败", data: err});
                        return;
                    }
                    if(result.affectedRows > 0){
                        res.send({code: 200, msg: "修改设备表成功", data: []});
                    }else{
                        res.send({code: 500, msg: "修改设备表失败", data: []});
                    }
                })
            }
        })
     })
})

// 删除设备表
router.delete("/:id", (req, res) => {
    console.log("===========删除设备表接口============");
    // 获取参数
    let {id} = req.params;
     // 拼接sql,删除多条数据
     let sql = `delete from dv_machinery where machinery_id in(${id})`;
    // 查询数据库
    db.query("删除设备表", sql, (err, result) => {
        if (err) {
            res.send({code: 500, msg: "删除设备表失败", data: err});
            return
        }
        if(result.affectedRows > 0){
            res.send({code: 200, msg: "删除设备表成功"})
        }else{
            res.send({code: 500, msg: "删除设备表失败"})
        }
    })
})


module.exports = router;